import { convertUrl } from '@/utils/apiAdaptive'
import { EventSourcePolyfill } from 'event-source-polyfill'
import tool from '@/utils/tool'
import { message } from 'ant-design-vue'
import { useSSEStore } from '@/store/sseStore'

// 生成客户端ID
const generateRandomNumber = () =>
	[...Array(10)].map(() => Math.random().toString(36).charAt(2) || Math.floor(Math.random() * 10)).join('')

export const initSse = (sseUrl) => {
	if (window.EventSource) {
		const sseStore = useSSEStore()
		let baseUrl = import.meta.env.VITE_API_BASEURL
		// 生产环境判断
		const isProd = import.meta.env.PROD
		let url = isProd
			? '/api' + convertUrl(sseUrl + generateRandomNumber())
			: baseUrl + convertUrl(sseUrl + generateRandomNumber())
		// 如果已有连接，先关闭
		if (sseStore.eventSource) {
			sseStore.disconnect()
		}
		const source = new EventSourcePolyfill(url, {
			headers: { token: tool.data.get('TOKEN') },
			heartbeatTimeout: 300000
		})
		sseStore.setEventSource(source)
		source.addEventListener('open', (e) => {
			sseStore.setConnected(true)
			console.log('SSE connection opened')
		})
		source.addEventListener('message', (e) => {
			try {
				sseStore.addMessage(JSON.parse(e.data))
			} catch (error) {
				console.error('Failed to parse SSE message:', error)
			}
		})
		source.addEventListener('error', (e) => {
			sseStore.setConnected(false)
			console.error('SSE connection error:', e)
			source.close()
			setTimeout(() => {
				if (!sseStore.isConnected) {
					initSse(sseUrl)
				}
			}, 3000)
		})
	} else {
		message.warning('该浏览器不支持消息功能').then((r) => {})
	}
}
